import React, { useRef, useState } from 'react';
import {
  ModalForm,
  ProFormRadio,
  ProFormTreeSelect,
  ProFormText,
} from '@ant-design/pro-components';
import type { ProFormInstance } from '@ant-design/pro-components';
import { useIntl, useAccess, useModel } from 'umi';
import { getTree } from '@/utils';
import { getRoleList, addItem, updateItem } from '@/services/role';
import { message } from 'antd';
import { getMenurule } from '@/services/menurule';

type AddEditProps = {
  visible: boolean;
  row?: Partial<API.RuleListItem>;
  onClose?: () => void;
  onSuccess?: () => void;
};

const AddEdit: React.FC<AddEditProps> = (props) => {
  const { initialState } = useModel('@@initialState');
  const { visible, row, onClose, onSuccess } = props;
  const [group_id, setGroupid] = useState<string | undefined>(undefined);
  const handleVisibleChange = (show: boolean) => {
    if (!show) {
      onClose?.();
    }
  };
  const intl = useIntl();
  const access = useAccess();
  const formRef = useRef<ProFormInstance>();
  const getRoles = async () => {
    const { data, code } = await getRoleList({ _all: 'ty' });
    if (code === 0) {
      return getTree(
        data.data.map((item: API.RuleListItem) => ({
          ...item,
          disabled: item.id === (row && row.id),
        })),
      );
    }
    return [];
  };
  const getMenus = async (query: any) => {
    const params: API.PageParams = { _all: 'ty', type: 'menu,btn,tag', ...query };
    const { data, code } = await getMenurule(params);
    if (code === 0) {
      return getTree(
        data.data.map((item: API.RuleListItem) => ({ ...item, id: item.id.toString() })),
      );
    }
    return [];
  };
  const handleSubmit = async (values: API.RuleListItem) => {
    if (!access.isAdmin) {
      if (!row || !initialState?.currentUser?.roles.includes(row?.id)) {
        message.warning(
          intl.formatMessage({ id: row ? 'public.selfRolePermission' : 'public.noAddPermission' }),
        );
        return true;
      }
    }
    const rules =
      typeof values.rules[0] === 'string'
        ? values.rules.join(',')
        : values.rules.map((item: API.RuleListItem) => item.value).join(',');
    const { code } = row
      ? await updateItem({ ...values, id: row.id, rules })
      : await addItem({ ...values, rules });
    if (code === 0) {
      message.success(intl.formatMessage({ id: 'public.successTips' }));
      if (row) {
        location.reload();
      } else {
        onSuccess?.();
      }
      return true;
    }
    return false;
  };
  return (
    <ModalForm
      formRef={formRef}
      title={
        intl.formatMessage({
          id: row ? 'public.edit' : 'public.add',
        }) +
        intl.formatMessage({
          id: 'public.role',
        })
      }
      width="640px"
      layout="horizontal"
      grid={true}
      // rowProps={{
      //   gutter: 24,
      // }}
      labelAlign="left"
      labelCol={{ span: 4 }}
      wrapperCol={{ span: 20 }}
      visible={visible}
      onVisibleChange={handleVisibleChange}
      modalProps={{ centered: true, destroyOnClose: true, maskClosable: false }}
      onFinish={handleSubmit}
      initialValues={
        row
          ? { ...row, rules: row.rules.split(',') }
          : {
              status: 0,
              show: 0,
              rules: [],
            }
      }
    >
      <ProFormTreeSelect
        colProps={{
          span: 24,
        }}
        name="pid"
        // initialValue={row && row.pid}
        label={intl.formatMessage({ id: 'public.pid' })}
        style={{ width: '100%' }}
        placeholder={intl.formatMessage({ id: 'public.placeholder.select' })}
        fieldProps={{
          // showArrow: false,
          // filterTreeNode: true,
          // showSearch: true,
          // dropdownMatchSelectWidth: false,
          // labelInValue: true,
          treeDefaultExpandAll: true,
          allowClear: true,
          // autoClearSearchValue: true,
          // multiple: true,
          treeNodeFilterProp: 'name',
          treeNodeLabelProp: 'name',
          fieldNames: {
            label: 'name',
            value: 'id',
          },
          onChange(val) {
            setGroupid(val);
          },
        }}
        request={getRoles}
        rules={[
          {
            required: true,
            message: intl.formatMessage({ id: 'public.rules.pid' }),
          },
        ]}
      />
      <ProFormText
        colProps={{
          span: 24,
        }}
        name="name"
        // initialValue={row ? row.path : ''}
        label={intl.formatMessage({ id: 'role.name' })}
        rules={[
          {
            required: true,
            message: intl.formatMessage({ id: 'role.rules.name' }),
          },
        ]}
      />
      <ProFormTreeSelect
        colProps={{
          span: 24,
        }}
        name="rules"
        // initialValue={row && row.pid}
        label={intl.formatMessage({ id: 'role.rule' })}
        style={{ width: '100%' }}
        placeholder={intl.formatMessage({ id: 'public.placeholder.select' })}
        fieldProps={{
          // showArrow: false,
          // filterTreeNode: true,
          // showSearch: true,
          // dropdownMatchSelectWidth: false,
          labelInValue: false,
          treeDefaultExpandAll: true,
          allowClear: true,
          // autoClearSearchValue: true,
          treeCheckable: true,
          treeCheckStrictly: true,
          multiple: true,
          maxTagCount: 4,
          treeNodeFilterProp: 'remark',
          treeNodeLabelProp: 'remark',
          fieldNames: {
            label: 'remark',
            value: 'id',
          },
        }}
        request={getMenus}
        params={{ group_id }}
        rules={[
          {
            required: true,
            message: intl.formatMessage({ id: 'role.rules.rules' }),
          },
        ]}
      />
      <ProFormRadio.Group
        colProps={{
          span: 24,
        }}
        label={intl.formatMessage({ id: 'role.show' })}
        name="show"
        // initialValue={row ? row.status : 1}
        options={[
          {
            value: 0,
            label: intl.formatMessage({ id: 'role.self' }),
          },
          {
            value: 1,
            label: intl.formatMessage({ id: 'role.all' }),
          },
        ]}
      />
      <ProFormRadio.Group
        colProps={{
          span: 24,
        }}
        label={intl.formatMessage({ id: 'public.status' })}
        name="status"
        // initialValue={row ? row.status : 1}
        options={[
          {
            value: 0,
            label: intl.formatMessage({ id: 'public.enabled' }),
          },
          {
            value: 1,
            label: intl.formatMessage({ id: 'public.disabled' }),
          },
        ]}
      />
    </ModalForm>
  );
};

export default AddEdit;
